"""
设备分析API路由
提供设备使用统计、告警分布等分析数据
"""
from flask import Blueprint, jsonify, request
from app.models.mongodb import mongodb
from app.models.mysql_db import db
from app.utils.auth import auth_required
from datetime import datetime, timedelta
import random

device_analysis_bp = Blueprint('device_analysis', __name__, url_prefix='/api/device')

@device_analysis_bp.route('/alert-distribution', methods=['GET'])
@auth_required
def get_alert_distribution(current_user):
    """获取设备告警分布数据"""
    try:
        time_range = request.args.get('timeRange', 'day')
        
        # 根据时间范围计算查询时间
        if time_range == 'day':
            start_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        elif time_range == 'week':
            start_time = datetime.now() - timedelta(days=7)
        elif time_range == 'month':
            start_time = datetime.now() - timedelta(days=30)
        else:
            start_time = datetime.now() - timedelta(days=1)
        
        # 模拟告警分布数据
        # 在实际应用中，这里应该从数据库查询真实的告警数据
        alert_distribution = [
            {"name": "正常", "value": random.randint(80, 120)},
            {"name": "温度异常", "value": random.randint(5, 15)},
            {"name": "湿度异常", "value": random.randint(3, 12)},
            {"name": "PM2.5超标", "value": random.randint(2, 8)},
            {"name": "设备离线", "value": random.randint(1, 5)}
        ]
        
        return jsonify({
            "code": 200,
            "message": "获取告警分布成功",
            "data": alert_distribution
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取告警分布失败: {str(e)}"
        }), 500

@device_analysis_bp.route('/usage', methods=['GET'])
@auth_required
def get_device_usage_stats(current_user):
    """获取设备使用情况统计"""
    try:
        device_id = request.args.get('deviceId')
        start_date = request.args.get('startDate')
        end_date = request.args.get('endDate')
        granularity = request.args.get('granularity', 'day')
        
        # 模拟设备使用情况数据
        usage_stats = []
        
        # 生成模拟的设备使用情况表格数据
        device_names = ['环境监测站-001', '环境监测站-002', '环境监测站-003', '环境监测站-004', '环境监测站-005']
        statuses = ['正常', '离线', '故障', '电量低']
        
        for i, name in enumerate(device_names):
            usage_stats.append({
                "id": f"device_{i+1}",
                "deviceName": name,
                "location": f"位置 {i+1}",
                "status": random.choice(statuses),
                "batteryLevel": random.randint(20, 100),
                "lastUpdate": (datetime.now() - timedelta(minutes=random.randint(1, 60))).strftime('%Y-%m-%d %H:%M:%S'),
                "todayUptime": f"{random.randint(18, 24)}小时",
                "dataCount": random.randint(50, 200)
            })
        
        return jsonify({
            "code": 200,
            "message": "获取设备使用统计成功",
            "data": usage_stats
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取设备使用统计失败: {str(e)}"
        }), 500

@device_analysis_bp.route('/status', methods=['GET'])
@auth_required
def get_device_status_data(current_user):
    """获取设备状态数据"""
    try:
        from app.models.device import Device
        
        user_id = request.args.get('userId')
        device_id = request.args.get('deviceId')
        start_date = request.args.get('startDate')
        end_date = request.args.get('endDate')
        
        # 查询设备信息
        if device_id:
            # 查询特定设备
            device = Device.query.filter_by(device_id=device_id).first()
            if not device:
                return jsonify({
                    "code": 404,
                    "message": "设备不存在"
                }), 404
                
            # 获取设备的最新环境数据
            latest_data = mongodb.db.environment_data.find_one(
                {'deviceId': device_id},
                sort=[('timestamp', -1)]
            )
            
            # 返回设备状态详情
            status_data = {
                "status": device.status,
                "lastActive": device.last_active.isoformat() if device.last_active else None,
                "battery": device.battery_level,
                "batteryLife": f"约{round(device.battery_level / 10)}小时",  # 假设每10%电量对应1小时
                "health": device.device_health, 
                "workMode": device.work_mode
            }
            
            # 如果有最新环境数据，添加到状态中
            if latest_data and 'data' in latest_data:
                env_data = latest_data['data']
                status_data.update({
                    "temperature": env_data.get('temperature', 0),
                    "humidity": env_data.get('humidity', 0),
                    "pm25": env_data.get('pm25', 0),
                    "pm10": env_data.get('pm10', 0),
                    "co2": env_data.get('co2', 0),
                    "tvoc": env_data.get('tvoc', 0) or env_data.get('formaldehyde', 0)
                })
        else:
            # 查询多个设备的统计信息
            devices = Device.query.all()
            online_count = sum(1 for d in devices if d.status == 'active')
            
            # 生成设备状态概览
            status_data = {
                "online_count": online_count,
                "offline_count": len(devices) - online_count,
                "total_count": len(devices),
                "online_rate": f"{int(online_count / len(devices) * 100)}%" if devices else "0%",
                "status_history": []
            }
            
            # 生成24小时的状态历史数据
            for hour in range(24):
                status_data["status_history"].append({
                    "time": f"{hour:02d}:00",
                    "online": random.randint(18, 25),  # 这部分仍使用模拟数据
                    "offline": random.randint(0, 3)
                })
        
        return jsonify({
            "code": 200,
            "message": "获取设备状态数据成功",
            "data": status_data
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取设备状态数据失败: {str(e)}"
        }), 500

@device_analysis_bp.route('/<device_id>/maintenance-records', methods=['GET'])
@auth_required
def get_device_maintenance_records(current_user, device_id):
    """获取设备维护记录"""
    try:
        # 模拟维护记录数据
        maintenance_records = []
        
        for i in range(5):
            maintenance_records.append({
                "id": f"maintenance_{i+1}",
                "date": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime('%Y-%m-%d'),
                "type": random.choice(['定期检查', '故障维修', '升级更新', '清洁保养']),
                "description": f"维护记录 {i+1} - 设备运行正常",
                "technician": f"技术员{i+1}",
                "status": random.choice(['已完成', '进行中', '待处理']),
                "cost": random.randint(100, 1000)
            })
        
        return jsonify({
            "code": 200,
            "message": "获取维护记录成功",
            "data": maintenance_records
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取维护记录失败: {str(e)}"
        }), 500

@device_analysis_bp.route('/export-data', methods=['GET'])
@auth_required
def export_device_data(current_user):
    """导出设备数据"""
    try:
        # 这里应该实现实际的数据导出逻辑
        # 返回成功消息，实际导出功能需要根据具体需求实现
        return jsonify({
            "code": 200,
            "message": "数据导出请求已提交，请稍后下载",
            "data": {
                "export_id": f"export_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
                "estimated_time": "2-5分钟"
            }
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"导出数据失败: {str(e)}"
        }), 500
